import mongoose from "mongoose";
import assert from 'assert'
import { createErrorMessage, ErrorMessage } from "@packages/shared";

/** 事务逻辑函数类型 */
export type TransactionFun = <T, U>(param: T, session: mongoose.ClientSession) => Promise<U>

/**
 * 事务处理
 * @param fun - 事务逻辑函数
 * @param param - 事务逻辑函数的参数
 */
export const _transaction = async <T>(
    fun: TransactionFun,
    param: T
) => {
    const session = await mongoose.startSession();

    try {
        session.startTransaction();

        // 这里执行逻辑
        let data = null;
        if (fun) data = await fun(param, session);

        // throw new Error(ErrorCode.UNKNOW_DB_ERROR)

        // 提交事务
        await session.commitTransaction();

        return data;

    } catch (error) {
        await session.abortTransaction();
        assert(false, createErrorMessage(ErrorMessage.DB_TRANSACTIONT))
    }


};
